package net.zjitc.servlet.cart;

import net.zjitc.daomain.Book;
import net.zjitc.service.BookService;
import net.zjitc.service.BookServiceImpl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by hasee on 2017/10/15.
 */
@WebServlet(name = "AddServlet",urlPatterns = "/addServlet")
public class AddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //从数据库找书
        String id =  request.getParameter("id");
        BookService bookService = new BookServiceImpl();
        Book book = bookService.findById(id);

        //获取用户购物车
        ArrayList<Book> cart = (ArrayList) request.getSession().getAttribute("cart");
        //如果不存在购物车,新建购物车,并添加商品
        if(cart == null){
            ArrayList<Book> c = new ArrayList();
            c.add(book);
            request.getSession().setAttribute("cart",c);
        }else {//以存在购物车,添加商品
            cart.add(book);
        }
        response.sendRedirect("/web/cart/cart.jsp");
    }
}
